package com.raspositos.guitarfrik.android;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Set;
import java.util.TreeSet;

import org.focuser.sendmelogs.LogCollector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.provider.BaseColumns;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.raspositos.guitarfrik.android.IntroMediaPlayer.ErrorMessenger;
import com.raspositos.guitarfrik.android.IntroMediaPlayer.State;
import com.raspositos.guitarfrik.android.Prefs.SongFilter;

public class Main extends Activity {

	
	private static final int DIALOG_SEND_LOG = 345350;
	 private static final int DIALOG_PROGRESS_COLLECTING_LOG = 3255;
	    private static final int DIALOG_FAILED_TO_COLLECT_LOGS = 3535122;
		private static final int DIALOG_REPORT_FORCE_CLOSE = 3535788;

	

	private final class ForceCloseDialogListener implements
				DialogInterface.OnClickListener {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					new AsyncTask<Void, Void, Boolean>() {
						@Override
						protected Boolean doInBackground(Void... params) {
							return mLogCollector.collect();
						}
						@Override
						protected void onPreExecute() {
							showDialog(DIALOG_PROGRESS_COLLECTING_LOG);
						}
						@Override
						protected void onPostExecute(Boolean result) {
							dismissDialog(DIALOG_PROGRESS_COLLECTING_LOG);
							if (result)
								mLogCollector.sendLog("luz.dev@gmail.com", "Error Log", "Play-Along");
							else
								showDialog(DIALOG_FAILED_TO_COLLECT_LOGS);
						}
						
					}.execute();
				}
				dialog.dismiss();

				
			}
		}

	private final class OnSongClickHandler implements OnItemClickListener {

		synchronized public void onItemClick(AdapterView<?> parent, View view,
				int pos, long id) {
//			Log.d("GuitarFrik", "OnSongClickHandler");
			if (imPlayer.getState() == State.INTRO
					|| imPlayer.getState() == State.PREPARED) {
//				Log.i("GuitarFrik", "Media Player In use :)");
				return;
			}
			final TrackDescriptor track = (TrackDescriptor) view.getTag();
			

			
			if (!track.equals(currentTrack)){
				markChron.stop();
				markChron.setVisibility(View.INVISIBLE);
				sectionBtn.setEnabled(false);
				sectionPlaying = false;
				currentSection = null;
				// PLAY by taping  the song
				imPlayer.setOnPlay(new OnPlay() {

				public void play() {
					chron.setBase(SystemClock.elapsedRealtime());
					chron.start();
					new Handler().post(new Runnable() {

						public void run() {
						
							
							final String[] items = getCurrentTrackSections();
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, android.R.layout.simple_spinner_item, items){
								public String getItem(int position) {
									return items[position];
								}
								
							};
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							sectionBtn.setAdapter(adapter);
							sectionBtn.setEnabled(true);
							marker.setEnabled(true);
							mCtrls.show();
						}
					});
				}

				public void stopped() {
					if (marker.isChecked() && marker.isEnabled() &&   currentTrack != null){
						marker.performClick();
					}
					chron.stop();
					markChron.stop();
				}
			});
				imPlayer.setSongSource(track.getLocation());
				imPlayer.setTrackSection(null);
				currentTrack = track;
			}
			chron.stop();
			imPlayer.play();
		}


	}

	/**
	 * Invoked whenever the another activity comes infront
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
//		Log.d("GuitarFrik", "onPause");

	}

	/**
	 * Invoked when the activity has been paused and is returning
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
//		Log.d("GuitarFrik", "onResume");
	}

	/**
	 * Invoked during creation after onCreate and when restoring after onRestart
	 * 
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		super.onStart();
//		Log.d("GuitarFrik", "onStart");
		ImageArrayAdapter gAdptr;
		try {
			gAdptr = createTracksAdapter();
		} catch (NoExternalStorageException e) {
			Log.e("GuitarFrik", "No cursor while querying external device", e);
			Toast.makeText(this, R.string.err_noext, Toast.LENGTH_LONG).show();
			return;
		}
		songs.setAdapter(gAdptr);
		songs.setOnItemClickListener(new OnSongClickHandler());
		marker.setEnabled(false);
		if (currentTrack != null) {
			// Find the view who has the current track
			songs.setSelection(gAdptr.findPosition(currentTrack));
			//PLAY by taping the play button on the controls
			imPlayer.setOnPlay(new OnPlay() {
				public void play() {
					chron.setBase(SystemClock.elapsedRealtime()
							- imPlayer.getCurrentPosition());
					chron.start();
					if (sectionPlaying){
						chron.setBase(SystemClock.elapsedRealtime());
						markChron.start();
					} else {
						marker.setEnabled(true);								
					}
				}

				public void stopped() {
					if (marker.isChecked() && marker.isEnabled() &&   currentTrack != null){
						marker.performClick();
					}
					chron.stop();
					markChron.stop();
				}
			});
			imPlayer.play();

		}
	}

	private ImageArrayAdapter createTracksAdapter()
			throws NoExternalStorageException {
		Cursor cur = this.managedQuery(Media.EXTERNAL_CONTENT_URI,
				new String[] { BaseColumns._ID, MediaColumns.DISPLAY_NAME,
						MediaColumns.TITLE, AudioColumns.ALBUM,
						AudioColumns.ALBUM_ID, MediaColumns.DATA,
						AudioColumns.ARTIST, AudioColumns.DURATION },
				getSongFilter(), new String[]{}, prefs.getSortBy());
		if (cur == null)
			throw new NoExternalStorageException();
		TrackDescriptor[] tracks = new TrackDescriptor[cur.getCount()];
		cur.moveToFirst();
		while (!cur.isAfterLast()) {
			tracks[cur.getPosition()] = TrackDescriptor.newTrackDescriptor(cur,
					this);
			cur.moveToNext();
		}
		ImageArrayAdapter gAdptr = new ImageArrayAdapter(this, tracks, prefs
				.getArtSize(), prefs.getArtSize(), ImageView.ScaleType.FIT_XY,
				android.R.drawable.screen_background_dark);
		cur.close();
		return gAdptr;
	}

	/**
	 * Invoked after the activity is no longer visible
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
//		Log.d("GuitarFrik", "onStop");
		chron.stop();
		if (sectionPlaying) {
			markChron.stop();
		}
		if (imPlayer.isPlaying()){
			imPlayer.pause();
		}
		mCtrls.hide();
		songs.invalidate();
	}

	/**
	 * Called after onStop when the activity will be offloaded from memory (Shut
	 * down)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
//		Log.d("GuitarFrik", "onDestroy");
		imPlayer.release();
		super.onDestroy();
	}

	/**
	 * Ivoked after onStop when the activity comes back
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		super.onRestart();
//		Log.d("GuitarFrik", "onRestart");
	}

	// private AudioManager aMgr;
	private MediaController mCtrls;
	// private MediaPlayer mPlayer;
	private MediaController.MediaPlayerControl mPCtrl;
	private TrackDescriptor currentTrack;
	private TrackSection currentSection;
	private View mView;
	// FOR RECORDING private ContentResolver cr;
	private Chronometer chron;
	private Prefs prefs;
	// private Vibrator vibr;
	private ToggleButton marker;
	private Chronometer markChron;
	// protected int sectionStartAt;
	// protected int sectionEndAt;
	protected boolean sectionPlaying;
	// protected CountDownTimer countDownTimer;
	private Spinner sectionBtn;
	private Gallery songs;
	private Spinner sortCombo;
	private Spinner filterCombo;
	private String activeFilter;
	private IntroMediaPlayer imPlayer;
	private LogCollector mLogCollector;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLogCollector = new LogCollector(this);
		CheckForceCloseTask task = new CheckForceCloseTask();
        task.execute();
		mView = getLayoutInflater().inflate(R.layout.main, null);
		setContentView(mView);
		chron = (Chronometer) mView.findViewById(R.id.Chronometer01);
		mCtrls = new MediaController(this, true);
		imPlayer = new IntroMediaPlayer(this, new ErrorMessenger() {
			
			public void post(int resource, Object... args) {
				Toast.makeText(Main.this, getResources().getString(resource, args), Toast.LENGTH_LONG).show();
			}
		});
		mPCtrl = new MediaController.MediaPlayerControl() {

			public int getBufferPercentage() {
				return 100;
			}

			public int getCurrentPosition() {
				return imPlayer.getCurrentPosition();
			}

			public int getDuration() {
				return imPlayer.getDuration();
			}

			public boolean isPlaying() {
				return imPlayer.isPlaying();
			}

			public void pause() {
				imPlayer.pause();
				chron.stop();
				markChron.stop();
				marker.setEnabled(false);
			}

			public void seekTo(int time) {
				chron.stop();
				imPlayer.seekTo(time);
				chron.setBase(SystemClock.elapsedRealtime()
						- imPlayer.getCurrentPosition());
				chron.start();
				if (sectionPlaying){
					markChron.stop();
					markChron.setVisibility(View.INVISIBLE);
					sectionPlaying = false;
					sectionBtn.setSelection(0,true);
				}
				marker.setEnabled(true);
			}

			public void start() {
				if (imPlayer.getState() != State.INTRO
						&& imPlayer.getState() != State.PREPARED) {
					imPlayer.setOnPlay(new OnPlay() {

						public void play() {
							chron.setBase(SystemClock.elapsedRealtime()
									- imPlayer.getCurrentPosition());
							chron.start();
							if (sectionPlaying){
								chron.setBase(SystemClock.elapsedRealtime());
								markChron.start();
							} else {
								marker.setEnabled(true);								
							}
						}

						public void stopped() {
							if (marker.isChecked() && marker.isEnabled() &&   currentTrack != null){
								marker.performClick();
							}
							markChron.stop();
							chron.stop();
						}
					});
					imPlayer.play();

				}
			}

			public boolean canPause() {
				return (imPlayer.getState() != State.INTRO
						|| imPlayer.getState() != State.PREPARED);
			}

			public boolean canSeekBackward() {
				return  (imPlayer.getState() != State.INTRO
						|| imPlayer.getState() != State.PREPARED);
			}

			public boolean canSeekForward() {
				return  (imPlayer.getState() != State.INTRO
					|| imPlayer.getState() != State.PREPARED);
			}

		};
		mCtrls.setMediaPlayer(mPCtrl);
		mCtrls.setAnchorView(mView);
		songs = (Gallery) mView.findViewById(R.id.SongList);
		((LinearLayout) mView.findViewById(R.id.LinearLayout01))
				.setOnClickListener(new View.OnClickListener() {

					public void onClick(View arg0) {
						mCtrls.show();
					}
				});
		((RelativeLayout) mView.findViewById(R.id.Main))
		.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				mCtrls.show();
			}
		});
		prefs = Prefs.getPrefs(this);
		if (prefs.isFirstTime()){
			new Thread(){
				public void run(){
					try {
						UglyWorkaround.workAround(Main.this);
						prefs.setNotFirstTime();
					} catch (IOException e) {
						final StringWriter err = new StringWriter();
						e.printStackTrace(new PrintWriter(err));
						new Handler().post(new Runnable() {
							public void run() {
								Toast.makeText(Main.this, err.toString(), Toast.LENGTH_LONG);
							}
						});
					}
				}
			}.start();
		}
		marker = (ToggleButton) mView.findViewById(R.id.Mark);
		markChron = (Chronometer) mView.findViewById(R.id.Chronometer02);
		marker.setOnClickListener(new OnClickListener() {
			private int sectionEndAt = -1;
			private int sectionStartAt = -1;

			public void onClick(View view) {
				if (!marker.isChecked() && currentTrack != null) {
					sectionEndAt = imPlayer.getCurrentPosition();
					if (sectionEndAt < sectionStartAt){
						sectionEndAt = imPlayer.getDuration();
					}
					markChron.stop();
					markChron.setVisibility(View.INVISIBLE);
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Main.this);
					builder.setTitle(R.string.section_name);
					builder.setItems(R.array.song_sections,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int index) {
									String sectionName = Main.this
									.getResources()
									.getStringArray(
											R.array.song_sections)[index];
									currentTrack
											.addSection(new TrackSection(
													currentTrack.getId(),
													sectionStartAt,
													sectionEndAt
															- sectionStartAt,
													sectionName));
									final String[] items = getCurrentTrackSections();
									ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, android.R.layout.simple_spinner_item, items){
										public String getItem(int position) {
											return items[position];
										}
										
									};
									adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
									sectionBtn.setAdapter(adapter);

								}
							});

					builder.create().show();

					
				} else {
					sectionEndAt = -1;
					markChron.setVisibility(View.VISIBLE);
					markChron.setBase(SystemClock.elapsedRealtime());
					markChron.start();
					sectionStartAt = imPlayer.getCurrentPosition();
					if (sectionStartAt - prefs.getIntroMiliSecs() < 0){
						sectionStartAt = 0;
					} else {
						sectionStartAt -= prefs.getIntroMiliSecs() ;
					}
				}
			}
		});
		sectionBtn = ((Spinner) mView.findViewById(R.id.SectionPlay));
		sectionBtn.setOnLongClickListener(new OnLongClickListener() {
			private TrackSection[] sections = null;
			public boolean onLongClick(View view) {
				if (currentTrack != null){
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Main.this);
					builder.setTitle(R.string.del_section);
					sections = currentTrack.getSections();
					
					// Build Array of Strings
					String[] items = new String[sections.length];
					for (int i = 0; i < sections.length; i++) {
						TrackSection ts = sections[i];
						items[i] = ts.getName() + ts.getIndex();
					}
					builder.setSingleChoiceItems(items, -1,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
									final	int item) {
									dialog.dismiss();
									AlertDialog.Builder builder = new AlertDialog.Builder(
											Main.this);
									builder.setCancelable(true);
									builder.setTitle(R.string.del_section);
									builder.setMessage(getResources().getString(R.string.del_conf_section, sections[item].getName()));
									builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
										
										public void onClick(DialogInterface subdiag, int arg1) {
											currentTrack.removeSection(sections[item]);
											final String[] items = getCurrentTrackSections();
											ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this, android.R.layout.simple_spinner_item, items){
												public String getItem(int position) {
													return items[position];
												}
												
											};
											adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
											sectionBtn.setAdapter(adapter);
										}
									}).create().show();
								}
					});
					builder.create().show();
				}
				return true;
			}
		});
		sectionBtn.setOnItemSelectedListener(new OnItemSelectedListener() {
//			private TrackSection[] sections = null;

			public void   onItemSelected(AdapterView<?> adapter, View view, int position, long row) {
									if(imPlayer.getState() == State.INTRO || imPlayer.getState() == State.PREPARED){
										int originalItem = 0;
										if (currentSection != null ){
											String currTrackName = currentSection.getName() + currentSection.getIndex();
											for(int i = 0; i < sectionBtn.getAdapter().getCount(); i++){
												if (currTrackName.equals(adapter.getItemAtPosition(i))){
													originalItem = i;
													break;
												}
											}
										}
										adapter.setSelection(originalItem);
										
												Toast.makeText(Main.this, R.string.err_into, Toast.LENGTH_SHORT).show();
												
										return;
									}
									if (position == 0) {
										imPlayer.setTrackSection(null);
										markChron.stop();
										markChron.setVisibility(View.INVISIBLE);
										marker.setEnabled(true);
										sectionPlaying = false;
										currentSection = null;
										imPlayer.setOnPlay(new OnPlay() {

											public void play() {
												chron.setBase(SystemClock
														.elapsedRealtime());
												chron.start();
											}

											public void stopped() {
												if (marker.isChecked() && marker.isEnabled() &&   currentTrack != null){
													marker.performClick();
												}
												markChron.stop();
												chron.stop();
											}
										});
									} else {
										imPlayer
												.setTrackSection(currentTrack.getSections()[position - 1]);
											currentSection = currentTrack.getSections()[position - 1];
										marker.setEnabled(false);
										sectionPlaying = true;
										markChron.setVisibility(View.VISIBLE);
										// mPlayer.pause();
										// mPlayer.seekTo(currentSection.getOffset());
										chron.stop();
										imPlayer.setOnPlay(new OnPlay() {

											public void play() {

												chron.setBase(SystemClock
														.elapsedRealtime()
														- currentSection
																.getOffset());
												chron.start();
												markChron.setBase(SystemClock
														.elapsedRealtime());
												markChron.start();
											}

											public void stopped() {
												if (marker.isChecked() && marker.isEnabled() &&   currentTrack != null){
													marker.performClick();
												}
												markChron.stop();
												chron.stop();
											}
										});
										imPlayer.play();

									}
//									dialog.dismiss();
								}



public void onNothingSelected(AdapterView<?> arg0) {
	
}

							});

		sortCombo = (Spinner) mView.findViewById(R.id.SortList);

		ArrayAdapter<Object> sortList = new ArrayAdapter<Object>(this,
				android.R.layout.simple_spinner_item, Prefs.SongSort.values()) {

			@Override
			public Object getItem(int position) {
				return getResources().getString(
						((Prefs.SongSort) super.getItem(position))
								.getStringId());
			}

		};
		sortList
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sortCombo.setAdapter(sortList);
		sortCombo.setSelection(prefs.getSongSort().ordinal());
		sortCombo.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> adapter, View view,
					int pos, long id) {
				prefs.setSongSort(pos);
				refreshTracks();
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		filterCombo = (Spinner) mView.findViewById(R.id.FilterCombo);

		ArrayAdapter<Object> filterList = new ArrayAdapter<Object>(this,
				android.R.layout.simple_spinner_item, Prefs.SongFilter.values()) {

			@Override
			public Object getItem(int position) {
				return getResources().getString(
						((Prefs.SongFilter) super.getItem(position))
						.getStringId());
			}

		};
		filterList
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		filterCombo.setAdapter(filterList);
		filterCombo.setSelection(Prefs.SongFilter.findFilter(prefs.getFilter())
				.ordinal());
		filterCombo.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> adapter, View view,
					int pos, long id) {
				// Log.d("GuitarFrik", "filterCombo.setOnItemSelectedListener:"
				// + pos);
				if (pos == Prefs.SongFilter.ARTIST.ordinal()) {
					// Log.d("GuitarFrik",
					// "filterCombo.setOnItemSelectedListener: ARTIST");
					Builder bld = new Builder(Main.this);
					bld.setTitle(R.string.txt_filter);
					Cursor c = managedQuery(Media.EXTERNAL_CONTENT_URI,
							new String[] { BaseColumns._ID,
									AudioColumns.ARTIST }, "", new String[]{},
							AudioColumns.ARTIST + " ASC");
					final Set<CharSequence> sca = new TreeSet<CharSequence>();
					c.moveToFirst();
					for (int i = 0; !c.isAfterLast(); i++) {
						sca.add(c.getString(c
								.getColumnIndex(AudioColumns.ARTIST)));
						c.moveToNext();
					}
					bld.setSingleChoiceItems(
							sca.toArray(new CharSequence[] {}), -1,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int sel) {
									String value = sca.toArray(new CharSequence[] {})[sel]
													.toString();
									((TextView)findViewById(R.id.LblFilter)).setText(getResources().getString(R.string.txt_filter) + " " + value);
									setFilter(
											Prefs.SongFilter.ARTIST,
											value);
									refreshTracks();
									dialog.dismiss();
								}
							});
					c.close();
	
					bld.show();
				} else if (pos == Prefs.SongFilter.SONG.ordinal()) {
					// Log.d("GuitarFrik",
					// "filterCombo.setOnItemSelectedListener: SONG");

					Builder bld = new Builder(Main.this);
					bld
							.setMessage(getResources().getString(
									Prefs.SongFilter.SONG.getStringId())
									+ getResources().getString(
											R.string.txt_filter_dlg));
					bld.setTitle(R.string.txt_filter);
					final EditText editText = new EditText(Main.this);
					bld.setView(editText);
					bld.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dlg,
										int arg1) {
									String value = editText
									.getText().toString();
									((TextView)findViewById(R.id.LblFilter)).setText(getResources().getString(R.string.txt_filter)
											+ getResources().getString(R.string.lbl_startswith,  value));
									setFilter(Prefs.SongFilter.SONG, value);
									refreshTracks();
								}
							});
					bld.show();
				} else {
					setFilter(Prefs.SongFilter.ALL, "");
					refreshTracks();
				}

			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		
		

	}

	class CheckForceCloseTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			return mLogCollector.hasForceCloseHappened();
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				showDialog(DIALOG_REPORT_FORCE_CLOSE);
			} 
		}
	}
	
	
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DIALOG_SEND_LOG:
		case DIALOG_REPORT_FORCE_CLOSE:
			Builder builder = new AlertDialog.Builder(this);
			String message;
			if (id==DIALOG_SEND_LOG)
				message = "Do you want to send me your logs?";
			else 
				message = "It appears this app has crashed, do you want to report it to me?";
			builder.setTitle("Warning")
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(message)
			.setPositiveButton("Yes", new ForceCloseDialogListener())
			.setNegativeButton("No", new ForceCloseDialogListener());
			dialog = builder.create();
			break;
		case DIALOG_PROGRESS_COLLECTING_LOG:
			ProgressDialog pd = new ProgressDialog(this);
			pd.setTitle("Progress");
			pd.setMessage("Collecting logs...");
			pd.setIndeterminate(true);
			dialog = pd;			
			break;
		case DIALOG_FAILED_TO_COLLECT_LOGS:
			builder = new AlertDialog.Builder(this);
			builder.setTitle("Error")
			.setMessage("Failed to collect logs.")
			.setNegativeButton("OK", null);
			dialog = builder.create();
			break;
		default:
			dialog = super.onCreateDialog(id);
		}
		return dialog;
	}

	
	protected void setFilter(Prefs.SongFilter filter, String value) {
		if (filter == SongFilter.ARTIST) {
			activeFilter = filter.getFilter() + " = '" + value + "'";
		} else if (filter == SongFilter.ALL) {
			activeFilter = filter.getFilter();
		} else {// SONG
			activeFilter = filter.getFilter() + " LIKE '" + value + "%'";
		}
	}

	private String getSongFilter() {
		return AudioColumns.IS_MUSIC + " != 0 "
				+ ("".equals(activeFilter) ? "" : " AND " + activeFilter);
	}

	
	private void refreshTracks() {
		ImageArrayAdapter gAdptr;
		try {
			gAdptr = createTracksAdapter();
		} catch (NoExternalStorageException e) {
			Log.e("GuitarFrik", "No cursor while querying external device", e);
			Toast.makeText(this, R.string.err_noext, Toast.LENGTH_LONG);
			return;
		}
		songs.setAdapter(gAdptr);
		if (currentTrack != null) {
			// Find the view who has the current track
			songs.setSelection(gAdptr.findPosition(currentTrack));
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_prefs){
			PreferenceActivity pa = new PrefsActivity();
			startActivity(new Intent(this,pa.getClass()));
		} else if (item.getItemId() == R.id.menu_help){
			Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/guitarfrik/wiki/Help"));
			startActivity(myIntent);
		} else if (item.getItemId() == R.id.menu_rgp && currentTrack != null){
			Intent myIntent;
			try {
				myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(StoreLinker.getLink(this, prefs, currentTrack)));
				startActivity(myIntent);
			} catch (UnsupportedEncodingException e) {
				final StringWriter err = new StringWriter();
				e.printStackTrace(new PrintWriter(err));
				new Handler().post(new Runnable() {
					public void run() {
						Toast.makeText(Main.this, err.toString(), Toast.LENGTH_LONG);
					}
				});
			}
			
		}

		return super.onOptionsItemSelected(item);
	}

	private String[] getCurrentTrackSections() {
		TrackSection[] sections = currentTrack.getSections();
		final String[] items = new String[sections.length + 1];
		items[0] = Main.this.getResources().getString(
				R.string.select_default);
		for (int i = 0; i < sections.length; i++) {
			TrackSection ts = sections[i];
			items[i + 1] = ts.getName() + ts.getIndex();
		}
		return items;
	}

}